import axios, { AxiosResponse } from '@ohos/axios';
import httpStreamService from '../ApiModel/stream';
import http from '@ohos.net.http';
export let MDPYTHON_IP="http://192.168.98.47:5000"
/**
 * 通用返回接口
 * 所有与后端相应的接口调用，都可以统一返回此类型。
 * 您可以根据需要为该接口添加更多通用字段。
 */
// export interface mdResponse {
//   result?: string;   // 一般返回的简要信息
//   success?: string;  // 若操作成功，后端可能返回的成功标识
//   message?: string;    // 若操作失败，后端可能返回的错误信息
// }
export interface mdResponse {
  success: number;
  content: string;
  message: string;
}

/**
 * 请求参数可以视情况保留不同的 Interface 定义，也可以在函数参数中直接写明字段类型。
 * 以下保留不同方法的请求体示例，仅供参考。
 */
/**
 * 这是一个示例，演示如何在 TypeScript 中使用 Axios
 * 来调用 server.py 中的各个接口方法
 */

// 以下示例请求体接口仅供参考，可根据实际需求进行扩展或修改
export interface AddUserRequest {
  user: string;
}

export interface CreateSpaceRequest {
  user: string;
  a_spaceId: string;
  newSpaceName: string;
}

export interface CreateDocRequest {
  user: string;
  a_spaceId: string;
  a_docId: string;
  newDocName: string;
}

export interface RenameDocRequest {
  user: string;
  a_spaceId: string;
  a_docId: string;
  newDocName: string;
}

export interface DeleteDocRequest {
  user: string;
  a_spaceId: string;
  a_docId: string;
}

export interface WriteDocRequest {
  user: string;
  a_spaceId: string;
  a_docId: string;
  content: string;
}

export interface RenameSpaceRequest {
  user: string;
  a_spaceId: string;
  newSpaceName: string;
}

export interface DeleteSpaceRequest {
  user: string;
  a_spaceId: string;
}

export interface MoveDocRequest {
  user: string;
  a_spaceId: string;
  a_docId: string;
  dest_a_spaceId: string;
  dest_a_docId: string;
}

export interface CopyDocRequest {
  user: string;
  a_spaceId: string;
  a_docId: string;
  dest_a_spaceId: string;
  dest_a_docId: string;
}
export interface ReadDocRequest {
  user: string;
  a_spaceId: string;
  a_docId: string;
}

export interface AgentPermRequest {
  user: string;
  a_spaceId: string;
  a_docId?: string;
  permChar: string;
  method: string;
}

export interface ShareRequest {
  user: string;
  a_spaceId: string;
  a_docId: string;
  permChar: string;
  share_user: string;
}

export interface LiteralSearchParams {
  user: string;
  query: string;
  efrt?: string; // 新增字段
  affSpaceId?: string; // 新增字段
  useRegex?: boolean;
}

export interface SemanticSearchRequest {
  user: string;
  query: string;
  efrt?: string; // 新增字段
  affSpaceId?: string; // 新增字段
}

export interface NoteAgentRequest {
  user: string;
  task: string;
  streamtype:number;
}

interface PermissionRequest {
  user: string;
  perm_nodeid: number;
  result: string;
}
export function parseContent<parseT>(result:mdResponse,asObject=true):parseT|undefined|string {
  let TAG="_:_parseContent"
  console.log(TAG, "entered", typeof result, result.success, result.message,
    JSON.stringify(result).replace(/\n+/g, ""))
  if (result.success >= 0) {
    try {
      if (asObject) {
        return JSON.parse(result.content)
      }
      else{
        return result.content as string
      }
    } catch (e) {
      console.error(TAG, JSON.stringify(e))
      return undefined
    }
  }
  return undefined
}
export function parseStrContent<parseT>(str:string,asObject=true):parseT|undefined|string {
  let TAG="_:_parseStrContent"
  console.log(TAG, "entered", typeof str,
    JSON.stringify(str).replace(/\n+/g, ""))
    try {
      if (asObject) {
        let obj:parseT= JSON.parse(str)
        console.log(TAG,"parsed stringify",JSON.stringify(obj))
        return obj
      }
      else{
        console.log(TAG,"returning str",str)
        return str
      }
    } catch (e) {
      console.error(TAG, JSON.stringify(e))
      return undefined
    }
}
export class mdTreeClient {
  baseURL: string;

  constructor() {
    this.baseURL = MDPYTHON_IP
  }

  /**
   * 添加用户
   * 对应 server.py 中 /addUser
   */
  public async addUser(req: AddUserRequest): Promise<mdResponse> {
    const response: AxiosResponse<mdResponse> = await axios.post<mdResponse>(
      `${this.baseURL}/mdtree/addUser`,
      req
    );
    return response.data;
  }

  /**
   * 创建空间
   * 对应 server.py 中 /createSpace
   */
  public async createSpace(req: CreateSpaceRequest): Promise<mdResponse> {
    const response: AxiosResponse<mdResponse> = await axios.post<mdResponse>(
      `${this.baseURL}/mdtree/createSpace`,
      req
    );
    return response.data;
  }

  /**
   * 创建文档
   * 对应 server.py 中 /createDoc
   */
  public async createDoc(req: CreateDocRequest): Promise<mdResponse> {
    const response: AxiosResponse<mdResponse> = await axios.post<mdResponse>(
      `${this.baseURL}/mdtree/createDoc`,
      req
    );
    return response.data;
  }

  /**
   * 重命名文档
   * 对应 server.py 中 /renameDoc
   */
  public async renameDoc(req: RenameDocRequest): Promise<mdResponse> {
    const response: AxiosResponse<mdResponse> = await axios.post<mdResponse>(
      `${this.baseURL}/mdtree/renameDoc`,
      req
    );
    return response.data;
  }

  /**
   * 删除文档
   * 对应 server.py 中 /deleteDoc
   */
  public async deleteDoc(req: DeleteDocRequest): Promise<mdResponse> {
    const response: AxiosResponse<mdResponse> = await axios.post<mdResponse>(
      `${this.baseURL}/mdtree/deleteDoc`,
      req
    );
    return response.data;
  }

  /**
   * 写文档内容
   * 对应 server.py 中 /writeDoc
   */
  public async writeDoc(req: WriteDocRequest): Promise<mdResponse> {
    const response: AxiosResponse<mdResponse> = await axios.post<mdResponse>(
      `${this.baseURL}/mdtree/writeDoc`,
      req
    );
    return response.data;
  }

  /**
   * 重命名空间
   * 对应 server.py 中 /renameSpace
   */
  public async renameSpace(req: RenameSpaceRequest): Promise<mdResponse> {
    const response: AxiosResponse<mdResponse> = await axios.post<mdResponse>(
      `${this.baseURL}/mdtree/renameSpace`,
      req
    );
    return response.data;
  }

  /**
   * 删除空间
   * 对应 server.py 中 /deleteSpace
   */
  public async deleteSpace(req: DeleteSpaceRequest): Promise<mdResponse> {
    const response: AxiosResponse<mdResponse> = await axios.post<mdResponse>(
      `${this.baseURL}/mdtree/deleteSpace`,
      req
    );
    return response.data;
  }

  /**
   * 移动文档
   * 对应 server.py 中 /moveDoc
   */
  public async moveDoc(req: MoveDocRequest): Promise<mdResponse> {
    const response: AxiosResponse<mdResponse> = await axios.post<mdResponse>(
      `${this.baseURL}/mdtree/moveDoc`,
      req
    );
    return response.data;
  }

  /**
   * 复制文档
   * 对应 server.py 中 /copyDoc
   */
  public async copyDoc(req: CopyDocRequest): Promise<mdResponse> {
    const response: AxiosResponse<mdResponse> = await axios.post<mdResponse>(
      `${this.baseURL}/mdtree/copyDoc`,
      req
    );
    return response.data;
  }

  /**
   * 读文档
   * 对应 server.py 中 /readDoc
   */
  public async readDoc(req: ReadDocRequest): Promise<mdResponse> {
    const response: AxiosResponse<mdResponse> = await axios.post<mdResponse>(
      `${this.baseURL}/affine/readDoc`,
      req
    );
    return response.data;
  }
  /**
   * 权限配置
   * 对应 server.py 中 /mdtree/agentpermission
   */
  public async agentPerm(req: AgentPermRequest): Promise<mdResponse> {
    const response: AxiosResponse<mdResponse> = await axios.post<mdResponse>(
      `${this.baseURL}/mdtree/agentpermission`,
      req
    );
    return response.data;
  }

  /**
   * 分享文档
   * 对应 server.py 中 /mdtree/share
   */
  public async share(req: ShareRequest): Promise<mdResponse> {
    const response: AxiosResponse<mdResponse> = await axios.post<mdResponse>(
      `${this.baseURL}/mdtree/share`,
      req
    );
    return response.data;
  }

  /**
   * 字面量搜索
   * 对应 server.py 中 /mdtree/literalsearch
   */
  public async literalSearch(req: LiteralSearchParams): Promise<mdResponse> {
    const response: AxiosResponse<mdResponse> = await axios.post<mdResponse>(
      `${this.baseURL}/mdtree/literalsearch`,
      req // 直接传递参数对象
    );
    return response.data;
  }

  /**
   * 语义搜索
   * 对应 server.py 中 /mdtree/semanticsearch
   */
  public async semanticSearch(req: SemanticSearchRequest): Promise<mdResponse> {
    const response: AxiosResponse<mdResponse> = await axios.post<mdResponse>(
      `${this.baseURL}/mdtree/semanticsearch`,
      req
    );
    return response.data;
  }
  public async grantPermission(req: PermissionRequest): Promise<mdResponse> {
    const response: AxiosResponse<mdResponse> = await axios.post<mdResponse>(
      `${this.baseURL}/mdtree/permission`,
      req
    );
    return response.data;
  }
  onNoteAgentEnd(){

  }
  // try {
  //   const parsed:naMessage =parseContent<naMessage>(data,true)
  //   if (parsed.success === 2 && parsed.message === "ask_approval") {
  //     // 暂停流或直接结束
  //     // 弹窗询问用户
  //     const userConfirm = confirm(`是否同意操作? operation=${parsed.operation}, node=${parsed.node_info}`);
  //     // 结束当前请求
  //     httpStreamService.cancel();
  //
  //     // 发起新的请求传递 用户同意or拒绝
  //     const body2 = {
  //       context_id: parsed.context_id,
  //       approve: userConfirm,
  //       // 其他必要信息
  //     };
  //     this.noteAgentStream(body2, onDataReceive, onEnd);
  //   } else {
  //     // 没有 ask_approval，正常处理 chunk
  //     onDataReceive(chunk);
  //   }
  // } catch (e) {
  //   onDataReceive(chunk);
  // }

  noteAgentStream(
    bodyJson:NoteAgentRequest,
    onReceive:(data:string)=>void,
    onEnd:()=>void
  ): void {
    let pathurl="/mdtree/noteagent_s"
    const TAG: string = "[MDrequestStream]"
    let requestOptions:http.HttpRequestOptions={
      method: http.RequestMethod.POST,
      header: [
        {
          'Content-Type': 'application/json'
        },
      ],
      extraData: JSON.stringify(bodyJson),
    };

    httpStreamService.onDataReceive((data: string) => {
      onReceive&&onReceive(data);
    });
    httpStreamService
      .requestHttp(this.baseURL+pathurl, requestOptions)
      .then((statusCode: number) => {
        console.info(TAG, "Request successful, status = " + statusCode);
        onEnd&&onEnd()
      })
      .catch((err: Error) => {
        console.error(TAG, "Request error: ", JSON.stringify(err));
        onEnd&&onEnd()
      });
  }
}


